﻿using B.S.Traceability.Domain;
using B.S.Traceability.ErrorCode;
using B.S.Traceability.Infra.Interfaces;
using B.S.Traceability.WebAPI.Read.Commands;
using MediatR;

namespace B.S.Traceability.WebAPI.Read.CommandHandlers
{
    public class GetShopsCommandHandler : IRequestHandler<GetShopsCommand, APIResult<APIPaging<Shops>>>
    {
        private readonly IBaseRepository<Shops> _shopsRepository;

        public GetShopsCommandHandler(IBaseRepository<Shops> shopsRepository)
        {
            _shopsRepository = shopsRepository;
        }

        public async Task<APIResult<APIPaging<Shops>>> Handle(GetShopsCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<Shops>> result = new APIResult<APIPaging<Shops>>();
            result.Code = APIEnum.Success;
            result.Msg = "查询成功";

            var list = _shopsRepository.GetAll();

            int TotalCount = list.Count();
            int TotalPage = (int) Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            list = list.OrderByDescending(p => p.ShopId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPaging<Shops> paging = new APIPaging<Shops>();
            paging.TotalCount = TotalCount;
            paging.TotalPage = TotalPage;
            paging.list = list.ToList();

            result.Data = paging;
            return await Task.FromResult(result);
        }
    }
}
